package com.wjx.mybatis.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisSessionUtil {
    private  ThreadLocal<SqlSession> session = new ThreadLocal<>();

    @Autowired
    private  SqlSessionFactory factory = null;

    private MyBatisSessionUtil(){}

    public static MyBatisSessionUtil me() {
        return new MyBatisSessionUtil();
    }

    public  SqlSession getSession() {
        SqlSession sqlSession = session.get();
        if(sqlSession == null) {
            sqlSession = factory.openSession();
            session.set(sqlSession);
        }
        return sqlSession;
    }

    public void closeSession() {
        SqlSession sqlSession = session.get();
        if(sqlSession != null) {
            //一定要清除缓存，否则会导致查询的结果不是数据库最新，而是缓存中的数据
            sqlSession.clearCache();
            sqlSession.close();
            session.set(null);
        }
    }
}
